document.addEventListener('DOMContentLoaded', function() {
    // 初始化图表
    initSalesChart();
    initUserSourceChart();
    initOrderStatusChart();
    
    // 时间范围切换
    document.getElementById('timeRange').addEventListener('change', function() {
        refreshDashboardData(this.value);
    });
    
    // 刷新按钮
    document.getElementById('refreshBtn').addEventListener('click', function() {
        const timeRange = document.getElementById('timeRange').value;
        refreshDashboardData(timeRange);
    });
    
    // 销售趋势图切换
    document.querySelectorAll('[data-metric]').forEach(btn => {
        btn.addEventListener('click', function() {
            document.querySelectorAll('[data-metric]').forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            updateSalesChart(this.dataset.metric);
        });
    });
});

function initSalesChart() {
    const ctx = document.getElementById('salesChart').getContext('2d');
    window.salesChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: JSON.parse(document.currentScript.getAttribute('data-labels')),
            datasets: [{
                label: '销售额',
                data: JSON.parse(document.currentScript.getAttribute('data-amounts')),
                borderColor: '#4e73df',
                backgroundColor: 'rgba(78, 115, 223, 0.05)',
                borderWidth: 2,
                tension: 0.4,
                fill: true
            }]
        },
        options: getChartOptions('¥')
    });
}

function initUserSourceChart() {
    const ctx = document.getElementById('userSourceChart').getContext('2d');
    window.userSourceChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: ['直接访问', '搜索引擎', '社交媒体', '推荐链接', '其他'],
            datasets: [{
                data: [35, 25, 20, 15, 5],
                backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc', '#f6c23e', '#e74a3b'],
                hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf', '#dda20a', '#be2617'],
                hoverBorderColor: "rgba(234, 236, 244, 1)",
            }]
        },
        options: {
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'right',
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return `${context.label}: ${context.raw}%`;
                        }
                    }
                }
            },
            cutout: '70%',
        }
    });
}

function initOrderStatusChart() {
    const ctx = document.getElementById('orderStatusChart').getContext('2d');
    window.orderStatusChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['待支付', '已支付', '已发货', '已完成', '已取消'],
            datasets: [{
                label: '订单数量',
                data: [12, 19, 8, 15, 3],
                backgroundColor: '#4e73df',
                hoverBackgroundColor: '#2e59d9',
            }]
        },
        options: getChartOptions('')
    });
}

function getChartOptions(prefix) {
    return {
        maintainAspectRatio: false,
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                    callback: function(value) {
                        return prefix + value;
                    }
                }
            }
        },
        plugins: {
            tooltip: {
                callbacks: {
                    label: function(context) {
                        return `${context.dataset.label}: ${prefix}${context.raw}`;
                    }
                }
            }
        }
    };
}

function refreshDashboardData(timeRange) {
    fetch(`/api/dashboard?range=${timeRange}`)
        .then(response => response.json())
        .then(data => {
            // 更新关键指标
            document.querySelector('[data-metric="totalSales"]').textContent = `¥${data.totalSales.toFixed(2)}`;
            document.querySelector('[data-metric="totalOrders"]').textContent = data.totalOrders;
            // ... 更新其他指标
            
            // 更新图表数据
            updateChartData(window.salesChart, data.salesChartData);
            updateChartData(window.userSourceChart, data.userSourceData);
            updateChartData(window.orderStatusChart, data.orderStatusData);
        });
}

function updateChartData(chart, newData) {
    chart.data.labels = newData.labels;
    chart.data.datasets.forEach((dataset, i) => {
        dataset.data = newData.datasets[i].data;
    });
    chart.update();
}

function updateSalesChart(metric) {
    const chart = window.salesChart;
    chart.data.datasets[0].label = metric === 'amount' ? '销售额' : '订单数';
    chart.data.datasets[0].data = metric === 'amount' 
        ? JSON.parse(document.currentScript.getAttribute('data-amounts'))
        : JSON.parse(document.currentScript.getAttribute('data-counts'));
    chart.options.scales.y.ticks.callback = function(value) {
        return metric === 'amount' ? '¥' + value : value;
    };
    chart.update();
}